<?php
namespace app\home\controller;
use think\Controller;
use think\Request;
use think\Db;
use think\Session;
require_once (APP_PATH . 'api/RewardApi.php');
require_once (APP_PATH . 'api/FinanceApi.php');
class Reg extends Base {
	//空操作
	public function _initialize(){
		parent::_initialize();
		define('SC_SYS','http://sksc.quyum99.com');
	}
	
	public function _empty(){
		header("HTTP/1.0 404 Not Found");
		$this->display('Public:404');
	}
	public function moni(){
		for($i = 1;$i<1000;$i++){
			sleep(1);
			$r[] = $this->moniReg();
			echo '成功';echo '<br>';
		}
		
	}

	public function moniReg(){
		$count = Db::name('App_member_relation')->count();
		if($count == 1){
			$order = 1;
			$quyu = 'left';
		}else{
			$now_order = $count+1;
			$num = $now_order%2;
			if($num == 0){
				$order = ceil($now_order/2);
				$quyu = 'left';
			}else{
				$order = floor($now_order/2);
				$quyu = 'righ';
			}
		}
		dump($count);
		dump($order);
		
		
		$jiedian = Db::name('App_member_relation')->where(array('order'=>$order))->find();
		dump($jiedian['member_id']);
		
		
		//随机生成
// 		$account = $this->getNewAccount();
		$list ['loginName'] = $count+1;
		$list ['loginPwd'] = md5('123456');
		$list ['createTime'] = time();
		$res = Db::name('Users')->insert($list);

		
		$list_relation['level'] = 1;
		$class = $this->getUserMoneyByLevel($list_relation['level']);
		
		$now_user = Db::name('Users')->where(array('loginName'=> $list ['loginName'] ))->find();
		$list_relation ['member_id'] = $now_user['userId'];
		$list_relation ['zhuceid'] = $jiedian['member_id'];
		$list_relation ['jiedianid'] = $jiedian['member_id'];
		$list_relation ['quyu'] = $quyu; // 分支
		$list_relation ['status'] = 1;//未激活
		$list_relation ['add_time']=time();
		$list_relation ['baodan'] = 1;
		$list_relation ['order'] = $count+1;
		//注册
		$ure = Db::name('App_member_relation')->insert ($list_relation);
		$finance = new \FinanceApi();
		$re[] = $finance->addFinance(1,1, '注册新会员，消耗注册积分', 2, $class['money'], 1);
			
		//注册成功小区表。积分表
		$this->afterReg($now_user['userId']);
		$reward = new \RewardApi();
		$re = $reward->begin($now_user['userId'],$class['money']);
		return $re; 
	}
	
	
	

	/**
	 * 内注册
	 * 6.8褚天恩
	 */
	public function index(){
		//三级联动
		$parent_id['parentId'] = 0;
		$region = Db::name('Areas')->where($parent_id)->select();
		$this->assign('region',$region);
		//dump($region);die();
		//三级联动结束
		$session = session::get();
		$jiedian_id = input('id');
		$quyu = input('quyu');
		if($jiedian_id){
			$jiedian_member = Db::name('Users')->where(array('userId'=>$jiedian_id))->find();
		}
		$tuijian_member = Db::name('Users')->where(array('userId'=>$session['USER_KEY_ID']))->find();
		$where['status'] = 1;
		$level = Db::name('App_level')->where($where)->select();
		//随机生成
		$account = $this->getNewAccount();
		$this->assign('account','zq'.$account);
		$this->assign('quyu',$quyu);
		$this->assign('jiedian',$jiedian_member);
		$this->assign('tuijian',$tuijian_member);
		$this->assign('level',$level);
		return $this->fetch();
	}
	
	public function area(){
		$parent_id['parentId'] = input('pro_id');
		$region = M('Areas')->where($parent_id)->select();
		$opt = '<option value="">--请选择市区--</option>';
		foreach($region as $key=>$val){
		    $opt .= "<option value='{$val['areaId']}'>{$val['areaName']}</option>";
		 }
		 //dump($opt);die();
		 echo $opt;
		
	}
	//通过节点ID查找上级
	protected function getNewAccount(){
		$loginName = $this->getRandomString(6);
		$member =  Db::name('Users')->where(array('loginName'=>$loginName))->find();
		if($member) {
			$loginName= $this->getNewAccount();
		}else{
			return $loginName;
		}
	}
	/**
	 * 随机生成用户名
	 * @param unknown $len
	 * @param string $chars
	 * @return string
	 */
	public function getRandomString($len, $chars=null){
	    if (is_null($chars)){
	        $chars = "0123456789";
	    }  
	    mt_srand(10000000*(double)microtime());
	    for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
	        $str .= $chars[mt_rand(0, $lc)];  
	    }
	    return $str;
	}
	/**
	 * 验证用户名是否处在
	 */
	public function checkout_user(){
		$account = I('account');
		$member = M('Member')->where(array('account'=>$account))->find();
		if($member){
			$data['info'] = '存在';
			$data['status'] = 1;
			return json($data);
		}else{
			$data['info'] = '不存在';
			$data['status'] = -1;
			return json($data);
		}
	}
	
	
	
	
	/**
	 * 外注册
	 */
	public function outreg(){
		
		return $this->fetch();
	}
	
	/**
	 * 注册登录
	 */
	public function add() {
		$Users = Db::name( "Users" );
		$session = session::get();
		$my_member_id = $session['USER_KEY_ID'];
		$loginName = strval(input('uname'));
		$user=$Users->where(array('loginName'=>$loginName.""))->find();
		if($loginName === ''){
			$data['info'] = "请填写用户名";
			$data['status'] = -1;
			return json($data);
		}
		if($user){
			$data['info'] = "用户名重复";
			$data['status'] = -1;
			return json($data);
		}
		if (empty ( $_POST ['pwd'] )) {
			$data['info'] = "请输入密码";
			$data['status'] = -2;
			return json($data);
		}
		if ( $_POST ['pwd']!=$_POST['twopwd'] ) {
			$data['info'] = "密码输入不相同";
			$data['status'] = -3;
			return json($data);
		}
		if ( $_POST ['pwd'] == $_POST['topwd'] ) {
			$data['info'] = "密码与二级密码相同";
			$data['status'] = -3;
			return json($data);
		}
		if (empty ( $_POST ['topwd'] )) {
			$data['info'] = "请输入二级密码";
			$data['status'] = -2;
			return json($data);
		}
		if ( $_POST ['topwd']!=$_POST['twotopwd'] ) {
			$data['info'] = "二级密码输入不相同";
			$data['status'] = -3;
			return json($data);
		}
		$idcard = input('shenfenzheng');
		$rr = Db::name('App_member_relation')->where(array('idcard'=>$idcard))->find();
		if(!empty($rr)){
			$data['info'] = "身份证号已存在";
			$data['status'] = -5;
			return json($data);
		}
		
// 		if (empty ( $_POST ['qu'] )) {
// 			$data['info'] = "请选择地区";
// 			$data['status'] = -5;
// 			$this->ajaxReturn($data);
// 		}
		if (empty($_POST ['level'])){
			$data['info'] = "请选择会员等级";  
			$data['status'] = -4;
			return json($data);
		}
		$jiedian = input('jiedianid');
		$quyu = input('quyu');
		//系统模式类型 
		$system_type = config("system_type");//1是双轨    2太阳线
		if($system_type == 2){
			
			
		}else{
			if (empty ($jiedian)) {
				$data['info'] = "请输入接点人";
				$data['status'] = -5;
				return json($data);
			}
			$contacts = Db::name('Users')->where("loginName = '".$jiedian."'")->find();//判断是否有这个接点人
			
			$jiedian_relation = Db::name('App_member_relation')->where(array('member_id'=>$contacts['userId']))->find();
			if(!$contacts){
				$data['info'] = "无此接点人";
				$data['status'] = -6;
				return json($data);
			}
			if($jiedian_relation['status'] < 1){
				$data['info'] = "接点人未开通";
				$data['status'] = -7;
				return json($data);
			}
			if (empty($quyu)) {
				$data['info'] = "分支不能为空";
				$data['status'] = -8;
				return json($data);
			}
			if ($quyu=='righ') {
				$where['jiedianid'] = $contacts['userId'];
				$where['quyu'] = 'left';
				$left = Db::name('App_member_relation')->where($where)->find();
				if(empty($left)){
					$data['info'] = "该用户左区还没有用户";
					$data['status'] = -9;
					return json($data);
				}
			}
			$map['jiedianid'] = $contacts['userId'];
			$map['quyu'] = input( 'quyu' );
			$fenzhi=Db::name('App_member_relation')->where($map)->find();
			if(!empty($fenzhi)){
				$data['info'] = "此分支已经有用户了";
				$data['status'] = -9;
				return json($data);
			}
			$list_relation ['jiedianid'] = $contacts['userId'];
			$list_relation ['quyu'] = input( 'quyu' ); // 分支
		}
		
		
		
		$list ['password'] = md5(input('pwd'));
		$tuijianid = input('tuijianid');
		$tuijianid = strval($tuijianid);//获取推荐信息
		if($tuijianid !== ''){
			$tuijian = Db::name('Users')->where("loginName = '$tuijianid'")->find();//判断是否有这个推荐人
			if (!$tuijian){
				$data['info'] = "无此推荐人";
				$data['status'] = -10;
				return json($data);
			}
		}else{
			$data['info'] = "请填写推荐人";
			$data['status'] = -15;
			return json($data);
		}
		
		$list_relation['level'] = input('level');
		$class = $this->getUserMoneyByLevel($list_relation['level']);
		//判断金额
// 		$account = Db::name('App_account_type')->where(array('jihuo'=>1))->find();//查看激活使用哪个积分
// 		$member_account = Db::name('App_member_account')->where(array('member_id'=>$my_member_id))->find();//用户积分余额
// 		if($member_account['account_type_'.$account['id']] < $class['money']){
// 			$data['info'] = '您的'.$account['name'].'不足';
// 			$data['status'] = -10;
// 			return json($data);
// 		}
		
		
		$list ['loginName'] = trim(input('uname'));
		$list ['loginPwd'] = md5(input('pwd'));
		$list ['payPwd'] = md5(input('topwd'));
		$list ['createTime'] = time();
		$res = Db::name('Users')->insert($list);
		$now_user = Db::name('Users')->where(array('loginName'=>$list ['loginName']))->find();
		$list_relation ['member_id'] = $now_user['userId'];
		$list_relation ['name'] = input('fullname');
		$list_relation ['idcard'] = input('shenfenzheng');
		$list_relation ['weixin'] = input('weixin');
// 		$list_relation ['address'] = input('address');
		$list_relation ['phone'] = input('tel');
		$list_relation ['sex'] = input('sex');
		$list_relation ['zhuceid'] = $tuijian['userId'];
		$list_relation ['ceng'] = $tuijian['ceng']+1;//钱包地址
		
		$list_relation ['status'] = 0;//未激活
		$list_relation ['add_time']=time();
// 		$list_relation ['qu'] = input('qu');
// 		$list_relation ['sheng'] = input('sheng');
// 		$list_relation ['shi'] = input('shi');
		$list_relation ['baodan'] = $session['USER_KEY_ID'];
		//注册
		$ure = Db::name('App_member_relation')->insert ($list_relation);
		$rs = $this->addChildren($tuijian['userId'],$now_user['userId']);
		if($ure){
			//注册成功小区表。积分表
			$this->afterReg($now_user['userId']);	
			$data['info'] = "注册成功";
			$data['status'] = 1;
			return json($data);
		}else{
			$data['info'] = "注册失败";
			$data['status'] = -11;
			return json($data);
		} 
	}
	/**
	 * 注册之后加左数和右数
	 * @param unknown $invite_id
	 * @param unknown $id
	 * @param unknown $info
	 * @return unknown
	 */
	public function addChildren($zhuce_id,$member_id){
		$res = Db::name('App_member_relation')->where(array('member_id' => $zhuce_id))->field('lft')->find()['lft'];
		$lft['lft'] = array('gt', $res);
		$rgt['rgt'] = array('gt', $res);
		Db::name('App_member_relation')->where($lft)->setInc('lft',2);
		Db::name('App_member_relation')->where($rgt)->setInc('rgt',2);
		$info['zhuceid'] = $zhuce_id;
		$info['lft'] = $res + 1;
		$info['rgt'] = $res + 2;
		$r = Db::name('App_member_relation')->where(array('member_id'=>$member_id))->update($info);
		return $r;
	}
	/**
	 * 注册成功之后积分表 小区奖表
	 * @param unknown $id
	 */
	
	public function afterReg($id){
		$data['member_id'] = $id;
		$re[] = Db::name('App_member_account')->add($data);
		return $re;
	}
	/**
	 * 获得唯一的6位编号
	 * @return unknown
	 */
	public function bianhao(){
		$number = rand(100000,999999);
		$list = M('Member')->where(array('number'=>$number))->select();
		if($list){
			$this->bianhao();	
		}else{
			return $number;
		}
	}
	
	
	
	/**
	 * ajax 发送手机号码
	 */
	public function sendPhone(){
		$phone = I('phone');
		$code=rand(1000, 9999);
		$tt = 'zc_'.$phone.'_'.$code;
		session(array('name'=>'code','expire'=>600));
		session('tt',$tt);  //设置session
		session('time',time());
		$msg="【创发】您的验证码为".$code."，请不要泄漏给他人！";//要发送的短信内容
		$re=sendSMS($phone, $msg);
		//     	dump($re);
		$result=preg_match_all('/[\x{4e00}-\x{9fff}]+/u', $re['1'], $matches);
		if($result == 1){
			$arr['status']=1;
			$arr['info']="发送成功";
		}else{
			$arr['status']= -1;
			$arr['info']="发送失败";
		}
		return json($arr);
	}
	
	
	
	
	
    /**
     * 显示注册界面
     */
    public function reg(){
    	//二级密码验证
    	//$this->checkTwoPwd();
    	//session('checkTwoPwd_success',null);
    	$pid=I('pid');$this->assign('pid',$pid);
    	$quyu=I('quyu');$this->assign('quyu',$quyu);
        return $this->fetch();
    }

   
   


    /**
     * ajax验证邮箱
     * @param string $email 规定传参数的结构
     * 
     */
    public function ajaxCheckEmail($email){
        $email = urldecode($email);
        $data = array();
        if(!checkEmail($email)){
            $data['status'] = 0;
            $data['msg'] = "邮箱格式错误";
        }else{
            $M_member = M('Member');
            $where['email']  = $email;
            $r = $M_member->where($where)->find();
            if($r){
                $data['status'] = 0;
                $data['msg'] = "邮箱已存在";
            }else{
            	//发送邮箱验证码
             	$code=rand(1000, 9999);
    			session('email_code',$code);  //设置session
             	$content = "<div>";
             	$content.= "您好，<br><br>您的注册验证码为：<br>";
            	$content.= $code;
             	$content.= "。请输入验证码完成验证。";
             	$rs = setPostEmail($this->config['EMAIL_HOST'],$this->config['EMAIL_USERNAME'],$this->config['EMAIL_PASSWORD'],$this->config['name'].'团队',$email,$this->config['name'].'团队[验证码]',$content);
         	 	$data['status'] = 1;
            	$data['msg'] = $rs;
            }
        }
        return json($data);
    }
    /**
     * ajax验证邮箱验证码
     * @param string $code 传来的验证码
     *
     */
    public function ajaxCheckEmailCode($code){
    	$code = urldecode($code);
    	if($code!=session('email_code')){
    		$data['status']=0;
    	}else{
    		$data['status']=1;
    	}
    	return json($data);
    }

	
}